// app.ts
interface IGlobalData {
  userInfo: any;
  logged: boolean;
}

interface IAppOption {
  globalData: IGlobalData;
  userInfoReadyCallback?: WechatMiniprogram.GetUserInfoSuccessCallback;
  checkUserLoginStatus(): Promise<void>;
  getOpenid(): Promise<string | null>;
}

// 定义云函数返回结果的接口
interface LoginResult {
  openid?: string;
  appid?: string;
  unionid?: string;
  event?: any;
}

App<IAppOption>({
  globalData: {
    userInfo: null,
    logged: false
  },
  onLaunch() {
    // 初始化云开发环境
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        env: 'cloud1-2gfboin3b3ab1c56',
        traceUser: true
      })
      console.log('云开发环境初始化成功')
      
      // 获取用户登录状态
      this.checkUserLoginStatus()
    }

    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },

  // 检查用户登录状态
  async checkUserLoginStatus() {
    try {
      // 获取本地存储的用户信息
      const userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.globalData.userInfo = userInfo
        this.globalData.logged = true
      } else {
        // 尝试获取云端用户信息
        const openid = await this.getOpenid()
        if (openid) {
          const db = wx.cloud.database()
          const userRecord = await db.collection('users').where({
            _openid: openid
          }).get()
          
          if (userRecord && userRecord.data.length > 0) {
            const userData = userRecord.data[0]
            this.globalData.userInfo = userData
            this.globalData.logged = true
            wx.setStorageSync('userInfo', userData)
          }
        }
      }
    } catch (error) {
      console.error('检查登录状态失败', error)
    }
  },

  // 获取用户openid
  async getOpenid() {
    try {
      const res = await wx.cloud.callFunction({
        name: 'login'
      })
      
      // 安全地访问返回结果
      const result = res.result as LoginResult
      if (result && result.openid) {
        return result.openid
      } else {
        console.error('云函数返回结果中没有openid', result)
        return null
      }
    } catch (error) {
      console.error('获取openid失败', error)
      return null
    }
  }
})